package com.shuwen.gcdj.common.util.file;

import java.lang.reflect.Field;
import java.util.Objects;
import java.util.regex.Pattern;

/***
 ** Created by ljf
 ** Date:2023/3/14
 *  excel字段校验类
 */
public class ExcelImportValid {
    /**
     * Excel导入字段校验
     *
     * @param object 校验的JavaBean 其属性须有自定义注解
     */
    public static void valid(Object object) throws Exception {
        //获取当前类的所有属性
        Field[] fields = object.getClass().getDeclaredFields();
        for (Field field : fields) {
            //设置可访问
            field.setAccessible(true);
            String name = field.getName();
            //属性的值
            Object fieldValue = null;
            try {
                //获取到字段的值
                fieldValue = field.get(object);
                if ("date".equals(name)){
                   if (!isDateValid((String) fieldValue)){
                       throw new Exception("日期格式不对");
                   }
                }
            } catch (IllegalAccessException e) {
                throw new Exception("导入参数检查失败");
            }
            //是否包含必填校验注解
            boolean isExcelValid = field.isAnnotationPresent(ExcelValid.class);
            //如果包含这个注解，并且获取到的值为null，抛出异常
            if (isExcelValid && Objects.isNull(fieldValue)) {
                throw new Exception("包含非空字段");
            }
        }
    }

    public static Boolean isDateValid(String date){
        String regexp = "[0-9]{4}-[0-9]{2}-[0-9]{2}";
        return Pattern.compile(regexp).matcher(date).matches();
    }

}
